package com.mvc.portal.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mvc.base.model.UserCompany;
import com.mvc.base.model.UserNotice;
import com.mvc.base.service.CompanyManager;
import com.mvc.base.service.UserCompanyManager;
import com.mvc.base.service.UserNoticeManager;
import com.mvc.finance.model.FinancePrivilege;
import com.mvc.finance.service.FinancePrivilegeManager;
import com.mvc.framework.service.PageManager;
import com.mvc.framework.web.PageController;
import com.mvc.portal.service.CUserManager;
import com.mvc.security.model.User;
import com.mvc.security.service.UserManager;

/**
 * 
 * @author snowpbx
 * @version V1.0 Create Time: 2012-10-5
 */
@Controller
@RequestMapping("extendUser")
public class ExtendUserController extends PageController<User> {
	public static final int	        USER_SALES	   = 1;
	public static final int	        USER_PURCHASER	= 2;
	public static final int	        USER_FINANCE	= 3;
	public static final int	        USER_ADMIN	   = 4;
	public static final int	        USER_HEAD	   = 5;
	public static final int	        USER_PRODUCE	= 6;

	public static final int	        USER_SUPPLIER	= 10;

	@Autowired
	private UserManager<User>	    userManager;

	@Autowired
	private UserCompanyManager	    userCompanyManager;

	@Autowired
	private FinancePrivilegeManager	financePrivilegeManager;

	@Autowired
	private CompanyManager	        companyManager;

	@Autowired
	private CUserManager	        cUserManager;

	@Autowired
	private UserNoticeManager	    userNoticeManager;

	@RequestMapping("getPurchaseUser")
	public String getPurchaseUser(ModelMap modelMap) {
		List<User> users = userManager.getUserByUserType(USER_PURCHASER);
		modelMap.addAttribute("users", users);
		return "jsonView";
	}

	@RequestMapping("getAll")
	public String getAll(ModelMap modelMap) {
		List<User> users = userManager.getAll();
		modelMap.addAttribute("users", users);
		return "jsonView";
	}

	@RequestMapping("selectEmailUsers")
	public String selectEmailUsers(HttpServletRequest request, HttpServletResponse response) {
		List<User> users = userManager.getAll();
		request.setAttribute("users", users);
		return "portal/selectEmailUsers";
	}

	protected String handleEdit(HttpServletRequest request, HttpServletResponse response, Integer id) throws Exception {
		if (null != id) {
			User user = userManager.get(id);
			request.setAttribute("entity", user);
			request.setAttribute("selected", userCompanyManager.getUserCompanyByUserId(user.getObjectId()));
			request.setAttribute("finances", financePrivilegeManager.getUserCompanyByUserId(user.getObjectId(), null));
			request.setAttribute("userNotices", userNoticeManager.getUserCompanyByUserId(user.getObjectId()));
		}
		request.setAttribute("companies", companyManager.getAll());
		return getFileBasePath() + "edit" + getActualArgumentType().getSimpleName();
	}

	protected String handleSave(HttpServletRequest request, ModelMap modelMap, User user) throws Exception {
		User savedUser = userManager.checkIfExistsUser(user);
		if (savedUser != null) {
			throw new RuntimeException("登录名不能重复");
		} else {
			cUserManager.save(user);
		}
		if (user.getType() != ExtendUserController.USER_SUPPLIER) {
			saveUserExtendInfo(request, user);
		}
		return "redirect:../extendUser/edit/" + user.getId() + getMessage("common.base.success", request);
	}

	protected void saveUserExtendInfo(HttpServletRequest request, User user) {
		Integer userId = user.getObjectId();
		String companyIds = request.getParameter("companyIds");
		saveUserCompany(userId, companyIds);

		String companyId1s = request.getParameter("companyId1s");
		String companyId2s = request.getParameter("companyId2s");
		saveUserFinancePrivilege(userId, companyId1s, companyId2s);

		String noticeTypes = request.getParameter("noticeTypes");
		saveUserNoticeType(userId, noticeTypes);
	}

	protected void saveUserNoticeType(Integer userId, String noticeTypes) {
		List<UserNotice> userNotices = new ArrayList<UserNotice>();
		if (StringUtils.isNotBlank(noticeTypes)) {
			String[] company = noticeTypes.split(";");
			for (int i = 0; i < company.length; i++) {
				UserNotice userCompanyPrivilege = new UserNotice();
				userCompanyPrivilege.setType(Integer.parseInt(company[i]));
				userCompanyPrivilege.setUserId(userId);
				userNotices.add(userCompanyPrivilege);
			}
		}
		userNoticeManager.saveUserNotices(userNotices, userId);
	}

	protected void saveUserFinancePrivilege(Integer userId, String companyId1s, String companyId2s) {
		List<FinancePrivilege> financePrivileges = new ArrayList<FinancePrivilege>();
		if (StringUtils.isNotBlank(companyId1s)) {
			String[] company = companyId1s.split(";");
			for (int i = 0; i < company.length; i++) {
				FinancePrivilege userCompanyPrivilege = new FinancePrivilege();
				userCompanyPrivilege.setCompanyId(Integer.parseInt(company[i]));
				userCompanyPrivilege.setUserId(userId);
				userCompanyPrivilege.setType(FinancePrivilege.TYPE_RECEIVEABLE);
				financePrivileges.add(userCompanyPrivilege);
			}
		}
		if (StringUtils.isNotBlank(companyId2s)) {
			String[] company = companyId2s.split(";");
			for (int i = 0; i < company.length; i++) {
				FinancePrivilege userCompanyPrivilege = new FinancePrivilege();
				userCompanyPrivilege.setCompanyId(Integer.parseInt(company[i]));
				userCompanyPrivilege.setUserId(userId);
				userCompanyPrivilege.setType(FinancePrivilege.TYPE_DUES);
				financePrivileges.add(userCompanyPrivilege);
			}
		}
		financePrivilegeManager.saveFinancePrivileges(financePrivileges, userId);
	}

	protected void saveUserCompany(Integer userId, String companyIds) {
		List<UserCompany> userCompanyPrivileges = new ArrayList<UserCompany>();
		if (StringUtils.isNotBlank(companyIds)) {
			String[] company = companyIds.split(";");
			for (int i = 0; i < company.length; i++) {
				UserCompany userCompanyPrivilege = new UserCompany();
				userCompanyPrivilege.setCompanyId(Integer.parseInt(company[i]));
				userCompanyPrivilege.setUserId(userId);
				userCompanyPrivileges.add(userCompanyPrivilege);
			}
		}
		userCompanyManager.saveUserCompanyPrivileges(userCompanyPrivileges, userId);
	}

	@Override
	public PageManager<User> getEntityManager() {
		return userManager;
	}

	@Override
	public String getFileBasePath() {
		return "security/";
	}
}
